import traceback

from PyQt5.QtCore import QFileInfo, QUrl, QObject, pyqtSlot, pyqtSignal
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QGridLayout, QPushButton


class Index:
    def renderIndex(self, main):
        """
        渲染程序首页
        """
        try:
            print('renderUi')
            # 实例化web对象
            self.webview = QWebEngineView(main)
            # 实例化web信道
            self.webviewChannel = QWebChannel(self.webview.page())
            # 注册PyQt交互对象
            self.interactObj = InteractObj(main)
            self.webviewChannel.registerObject("interactObj", self.interactObj)
            print('renderUi2')
            # 绑定web信道至web对象
            self.webview.page().setWebChannel(self.webviewChannel)
            # 加载web网页
            self.webview.page().load(QUrl(QFileInfo('view/index.html').absoluteFilePath()))
            # self.webview.page().load(QUrl("http://www.pyqt5_learning.com"))
            print('renderUi3')

            testButton = QPushButton("python按钮1")
            testButton.clicked.connect(main.testButtonCallback)

            testButton2 = QPushButton("python按钮2")
            testButton2.clicked.connect(main.testButton2Callback)

            # 渲染页面
            grid = QGridLayout()
            grid.setSpacing(0)
            grid.addWidget(self.webview, 1, 1, 1, 1)
            grid.addWidget(testButton, 2, 1, 1, 1)
            grid.addWidget(testButton2, 3, 1, 1, 1)
            grid.setContentsMargins(0, 0, 0, 0)
            main.setLayout(grid)
        except:
            print('未知异常')
            print(traceback.format_exc())

    def postMessageToHtml(self, message):
        """
        发送消息至html
        :param message:
        """
        print(message)
        self.interactObj.pyMessage.emit(message)

    def evalJS(self, method, param):
        """
        执行js方法
        :param method:
        :param param:
        """
        print(method + "('" + param + "')")
        self.webview.page().runJavaScript(method + "('" + param + "')")


class InteractObj(QObject):
    pyMessage = pyqtSignal(str)

    def __init__(self, parent=None):
        super().__init__(parent)

    @pyqtSlot(str)
    def jsPostMessage(self, msg):
        """
        暴露给html的js对象方法
        :param msg:
        """
        print("jsPostMessage:" + msg)
